import {compileToFunctions} from '../../compiler'
import {mountComponents} from './lifecycle'

export function initMixin(Vue) {

  Vue.prototype._init = function (options) {
    const vm = this

    vm.$options = options || {}

    // 如果有 el 则开始 挂载
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }

  Vue.prototype.$mount = function (el) {
    const vm = this

    el = (typeof el === 'string' && el.startsWith('#'))
      ? document.querySelector(el)
      : el

    const options = vm.$options

    // 优先级 render function > template > el.outerHTML
    if (!options.render) {
      let template = options.template || ''
      if (!template && el) {
        template = el.outerHTML
      }

      const {render} = compileToFunctions(template)
      options.render = render
    }

    mountComponents(vm, el)
  }
}
